import { useEffect, useMemo, useState, useCallback } from "react";
import request from "../../api/request";
import style from "./index.module.css";
import { List, Image, Button, Toast } from "antd-mobile";
import { Dropdown } from "antd-mobile";
import Cityslice from "../../compoents/Cityslice/Index";
// import { useDispatch } from "react-redux";
import Keshi from '../../compoents/Keshi/Index'
import { useDispatch, useSelector } from "react-redux";
import type { RootState } from "../../store/store";
import { setCurrentCity } from "../../store/UseStateList";
import { setCurrentkeshi } from "../../store/UseStatekeshi";
function Index() {
  type DoctorItem = {
    doctorimage?: string
    doctorcity?: string
    textdescword?: string
    doctordescword?: string
    doctorflag?: number
    doctorprice?: number
    doctorid?: number
    doctorgood?: number
    doctorname?: string
    doctorstate?: string
    socolv?: string
  }
  const [doctor, setDoctor] = useState<DoctorItem[]>([]);
  const pageCode = 1;
  const pageSize = 10;
  const dispatch = useDispatch();
  // 从仓库读取：城市与科室
  const city = useSelector((state: RootState) => state.UseStateList.currentCity);
  const selectedDept = useSelector((state: RootState) => state.useStatekeshi.currentCity);
  // 下拉项标题来源于仓库
  const deptTitle = useMemo(() => city || "全国", [city]);
  const deptTitleKeshi = useMemo(() => selectedDept || "全部科室", [selectedDept]);
  // 控制 Dropdown 展开/收起
  const [dropdownActiveKey, setDropdownActiveKey] = useState<string | null>(null);
  // 未选择时不传 admin，避免影响结果
  const admin = selectedDept || "";
  const [sortTag, setSortTag] = useState<number | null>(null);
  const [order, setOrder] = useState<"desc" | "asc" | "">("");

  const getDoctor = useCallback(async () => {
    try {
      const params: Record<string, string | number> = {
        pageCode,
        pageSize,
      };
      if (city && city !== "全国") params.city = city;
      if (admin && admin !== "全部科室") params.admin = admin;
      if (sortTag !== null) params.tag = String(sortTag);
      if (order) params.order = order;

      const res = (await request.get("/api/doctor/list", { params })) as unknown as {
        code: number;
        data: DoctorItem[];
        msg?: string;
      };
      console.log("医生列表", res);
      if (res.code === 20000) {
        setDoctor(res.data);
      } else {
        setDoctor([]);
        Toast.show(res?.msg || "获取医生列表失败");
      }
    } catch (err: unknown) {
      console.error("获取医生列表异常", err);
      setDoctor([]);
      Toast.show("服务器开小差了 (500)");
    }
  }, [pageCode, pageSize, city, admin, sortTag, order]);

  useEffect(() => {
    getDoctor();
  }, [getDoctor]);


  type OfficeItem = { adminname: string; adminchildrenname: string }
  const [keshi, setKeshi] = useState<OfficeItem[]>([]);
  

  const getKeshi = useCallback(async () => {
    try {
      const res: { code: number; data: OfficeItem[]; msg?: string } = await request.get("/api/office/list");
      console.log("科室数据", res);
      if (res.code === 20000) {
        setKeshi(res.data);
      } else {
        setKeshi([]);
      }
    } catch (err) {
      console.error("获取科室异常", err);
      setKeshi([]);
    }
  }, []);

  useEffect(() => {
    getKeshi();
  }, [getKeshi]);

  
  return (
    <div>
      <List>
        <Dropdown activeKey={dropdownActiveKey} onChange={setDropdownActiveKey}>
        <Dropdown.Item key="more" title={deptTitleKeshi}>
          <Keshi data={keshi} onSelect={(dept)=>{ dispatch(setCurrentkeshi(dept)); setDropdownActiveKey(null); }} />
          </Dropdown.Item>

          <Dropdown.Item key="sorter" title={deptTitle}>
           <Cityslice onSelect={(c)=>{ dispatch(setCurrentCity(c)); setDropdownActiveKey(null); }} />
          </Dropdown.Item>

          <Dropdown.Item key="filter" title="筛选">
            <List style={{ width: "100%" }}>
              {[
                "默认排序",
                "接诊人次从多到少",
                "好评率从高到低",
                "响应时间从短到长",
              ].map((label) => (
                <List.Item
                  key={label}
                  arrowIcon={false}
                  style={{
                    textAlign: "center",
                    fontSize: 'var(--adm-font-size-main)',
                    color: 'var(--adm-color-text)'
                  }}
                  onClick={() => {
                    // 选项与接口参数映射
                    if (label === "默认排序") {
                      setSortTag(null);
                      setOrder("");
                    } else if (label === "接诊人次从多到少") {
                      setSortTag(1);
                      setOrder("desc");
                    } else if (label === "好评率从高到低") {
                      setSortTag(2);
                      setOrder("desc");
                    } else if (label === "响应时间从短到长") {
                      setSortTag(3);
                      setOrder("asc");
                    }
                    setDropdownActiveKey(null);
                    getDoctor();
                  }}
                >
                  <span style={{ color: (
                    (label === "默认排序" && !sortTag && !order) ||
                    (label === "接诊人次从多到少" && sortTag === 1 && order === 'desc') ||
                    (label === "好评率从高到低" && sortTag === 2 && order === 'desc') ||
                    (label === "响应时间从短到长" && sortTag === 3 && order === 'asc')
                  ) ? "#1677ff" : "inherit" }}>{label}</span>
                </List.Item>
              ))}
            </List>
          </Dropdown.Item>
        </Dropdown>

        <div></div>
        {doctor.length > 0 &&
          doctor.map((item, index) => (
            <List.Item
              key={index}
              // onClick={() => goDoctorDetail(item.doctorid)}
              className={style.doctorCard}
              prefix={
                <Image
                  src={item.doctorimage}
                  className={style.avatar}
                  fit="cover"
                  width={48}
                  height={48}
                />
              }
              description={
                <div className={style.desc}>
                  <div className={style.hospitalLine}>
                    <span>{item.doctorcity}</span>
                    <span className={style.socoSpamce}>
                      {item.textdescword}
                    </span>
                  </div>

                  <div className={style.tags}>
                    <span className={style.tag}>图文咨询</span>
                    <span className={style.tag}>电话咨询</span>
                    <span className={style.tag}>视频咨询</span>
                  </div>

                  <div className={style.expert}>
                    {item.doctordescword?.substring(0, 20)}
                  </div>

                  <div className={style.stats}>
                    <span>
                      好评率
                      <span className={style.haoping}>
                        {((item.doctorflag || 0) * 100).toFixed(0)}
                      </span>
                      %
                    </span>
                    <span className={style.statDot}>|</span>
                    <span>
                      锦旗{" "}
                      <span className={style.haoping}>
                        {(item.doctorprice || 0).toFixed(0)}
                      </span>
                    </span>
                    <span className={style.statDot}>|</span>
                    <span>
                      浏览人数{" "}
                      <span className={style.haoping}>
                        {item.doctorid || 0}
                      </span>
                    </span>
                  </div>
                  <div className={style.bottomRow}>
                    <div className={style.priceBox}>
                      <span className={style.priceNumber}>
                        ￥{item.doctorgood || 0}起
                      </span>
                    </div>
                    <Button size="mini" color="primary">
                      问医生
                    </Button>
                  </div>
                </div>
              }
            >
              <div className={style.titleRow}>
                <span className={style.name}>{item.doctorname}</span>
                <div className={style.meta}>
                  <span className={style.badgePrimary}>{item.doctorstate}</span>
                  <span className={style.badgeLevel}>{item.socolv}</span>
                </div>
              </div>
            </List.Item>
          ))}
          
      </List>
    </div>
  );
}

export default Index;
